<?php
require_once(Path::getPath('smarty_class').'Smarty.class.php');
/**
 * Description of Template
 *
 * @author josema
 */
class Template extends Smarty {

    private $template_vars = array();

    /**
     * @todo    Meter dentro de un config
     * @var <type>
     */
    private $url_base = '/economy/rw/';

    function  __construct() {
        parent::__construct();

        $this->template_dir = Path::getPath('templates');
        $this->compile_dir = Path::getPath('smarty') . "templates_c/";
        $this->config_dir = Path::getPath('smarty') . "configs/";
        $this->cache_dir = Path::getPath('smarty') . "cache/";
        $this->caching = false;
        //$this->debugging = true;
        //$this->debug_tpl = 'debug.tpl';

        // A continuación de la Configuracion de Smarty:
        $this->left_delimiter = "{{";
        $this->right_delimiter = "}}";
    }

    /**
     * Adds a new variable to the template.
     * @param string $name
     * @param string $value
     */
    public function add($name, $value){
        // Todavia no está inicializada, anyadimos tipo basico
        if(!isset ($this->template_vars[$name]))
            $this->template_vars[$name] = $value;
        // Si ya existe pero no es un array, solo es un elemento, la hacemos array
        else if (!is_array($this->template_vars[$name]))
            $this->template_vars[$name] = array($this->template_vars[$name], $value);
        // Si ya existe y es un array, metemos el siguiente elemento al array o hacemos un merge
        else
            if(is_array($value))
                $this->template_vars[$name] = array_merge ($this->template_vars[$name], $value);
            else 
                array_push ($this->template_vars[$name], $value);

            //print_r($this->template_vars);
    }

    public function addObjects($name, $value){
        $tmp = array();
        foreach ($value as $key => $obj){
            $tmp[] = $obj->toArray();
        }
        $this->add($name, $tmp);
    }

  
    public function display($template, $cache_id = null, $compile_id = null, $parent = null){
        $this->populate();

        parent::display($template, $cache_id, $compile_id, $parent);
    }

    public function  fetch($template, $cache_id = null, $compile_id = null, $parent = null, $display = false) {
        $this->populate();

        return parent::fetch($template, $cache_id, $compile_id, $parent, $display);
    }

    /**
     * Assigns all the variables that we have in our templates to the smarty system.
     */
    private function populate(){
        foreach ($this->template_vars as $key => $value)
            $this->assign ($key, $value);

        $this->assign('url_base', $this->url_base);
    }
}
?>
